﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Common
{
    public class BaseDBConfig
    {
        /// <summary>
        /// 目前是多库操作，默认加载的是appsettings.json设置为true的第一个db连接。
        /// </summary>
        public static (List<MutiDBOperate> allDbs, List<MutiDBOperate> slaveDbs) MutiConnectionString => MutiInitConn();

        private static (List<MutiDBOperate> allDbs, List<MutiDBOperate> slaveDbs) MutiInitConn()
        {
            List<MutiDBOperate> listdatabase = AppSettings.App<MutiDBOperate>("DBS").Where(i => i.Enabled).ToList();
            foreach (var i in listdatabase)
            {
                SpecialDbString(i);
            }

            List<MutiDBOperate> listdatabaseSimpleDB = new List<MutiDBOperate>();//单库
            List<MutiDBOperate> listdatabaseSlaveDB = new List<MutiDBOperate>();//从库

            // 单库，且不开启读写分离，只保留一个
            if (!AppSettings.App(new string[] { "CQRSEnabled" }).ObjToBool() && !AppSettings.App(new string[] { "MutiDBEnabled" }).ObjToBool())
            {
                if (listdatabase.Count == 1)
                {
                    return (listdatabase, listdatabaseSlaveDB);
                }
                else
                {
                    var dbFirst = listdatabase.FirstOrDefault(d => d.ConnId == AppSettings.App(new string[] { "MainDB" }).ObjToString());
                    if (dbFirst == null)
                    {
                        dbFirst = listdatabase.FirstOrDefault();
                    }
                    listdatabaseSimpleDB.Add(dbFirst);
                    return (listdatabaseSimpleDB, listdatabaseSlaveDB);
                }
            }


            // 读写分离，且必须是单库模式，获取从库
            if (AppSettings.App(new string[] { "CQRSEnabled" }).ObjToBool() && !AppSettings.App(new string[] { "MutiDBEnabled" }).ObjToBool())
            {
                if (listdatabase.Count > 1)
                {
                    listdatabaseSlaveDB = listdatabase.Where(d => d.ConnId != AppSettings.App(new string[] { "MainDB" }).ObjToString()).ToList();
                }
            }

            return (listdatabase, listdatabaseSlaveDB);
        }

        /// <summary>
        /// 定制Db字符串
        /// 目的是保证安全：优先从本地txt文件获取，若没有文件则从appsettings.json中获取
        /// </summary>
        /// <returns></returns>
        private static MutiDBOperate SpecialDbString(MutiDBOperate mutiDBOperate)
        {
            switch (mutiDBOperate.DbType)
            {
                case DataBaseType.Sqlite:
                    mutiDBOperate.Connection = $"DataSource=" + Path.Combine(Environment.CurrentDirectory, mutiDBOperate.Connection);
                    break;
                case DataBaseType.SqlServer:
                    mutiDBOperate.Connection = DifDBConnOfSecurity(@"D:\my-file\dbCountPsw1_SqlserverConn.txt", mutiDBOperate.Connection);
                    break;
                case DataBaseType.MySql:
                    break;
                case DataBaseType.Oracle:
                    break;
                default:
                    break;
            }

            return mutiDBOperate;
        }

        private static string DifDBConnOfSecurity(params string[] conn)
        {
            foreach (var item in conn)
            {
                try
                {
                    if (File.Exists(item))
                    {
                        return File.ReadAllText(item).Trim();
                    }
                }
                catch (System.Exception) { }
            }

            return conn[conn.Length - 1];
        }


    }
}
